let myChart = null;
let interval = null;

function getHotList() {
    const main = $('#main');
    main.empty();
    initOneDiv(main)
    initTowDiv(main)
    createInterVal()

}

function getSingerList(pageNum, pageSize){
    return new Promise((resolve, reject) => {
        $.ajax({
            url: 'singerList/getSingerList',
            type: 'GET',
            data: {
                pageNum: pageNum,
                pageSize: pageSize
            },
            dataType: 'json',
            success: function(response) {
                resolve(response); // 解析服务器返回的 URL
            },
            error: function(xhr) {
                reject(new Error(xhr.responseText || '请求失败'));
            }
        });
    })
}

function initOneDiv(main) {
    const newDiv1 = $('<div>', {
        id: 'ranking',
        class: 'ranking-parent'
    });

    let noList = [];
    let noTextList = [];

    const No1 = $('<img>', {
        src: '/img/error.jpg',
        title: '点击跳转查看'
    });
    const No2 = $('<img>', {
        src: '/img/error.jpg',
        title: '点击跳转查看'
    });
    const No3 = $('<img>', {
        src: '/img/error.jpg',
        title: '点击跳转查看'
    });
    const No1Text = $('<p>', {
        text: ''
    });
    const No2Text = $('<p>', {
        text: ''
    });
    const No3Text = $('<p>', {
        text: ''
    });

    noList.push(No1, No2, No3);
    noTextList.push(No1Text, No2Text, No3Text);
    for (let i = 0; i < noList.length; i++) {
        let temp = i + 1
        let item = noList[i]
        item.attr('id', 'No' + temp)
        item.attr('onclick', 'window.open("https://kuwo.cn/singer_detail/336", "_blank")')
        item.addClass('ranking-No' + temp)
        newDiv1.append(item)
    }
    for (let i = 0; i < noTextList.length; i++) {
        let temp = i + 1
        let item = noTextList[i]
        item.attr('id', 'No' + temp + 'Text')
        item.attr('onclick', 'window.open("https://kuwo.cn/singer_detail/336", "_blank")')
        item.addClass('ranking-No' + temp + '-text')
        newDiv1.append(item)
    }
    main.append(newDiv1);
    getTopThree()

}

var singerInfo = [[0, 0, 0], [0, 0, 0]]
var singerName = []

// 初始化第二个div
function initTowDiv(main) {
    const newDiv2 = $('<div>', {
        id: 'container',
        class: 'container-style'
    });

    const input = [];

    for (let i = 0; i < 2; i++) {
        input.push($('<input>', {
            placeholder: "请输入歌手名称",
            type: 'text',
            width: '90px',
            id: 'inputSinger' + (i + 1),
            class: 'singer-input-style'
        }))
    }

    const btnDiv = $('<div>', {
        id: 'btnDiv',
        class: 'btnDiv-style'
    });
    const line = $('<div>', {
        id: 'line',
        class: 'line-style'
    });

    const loadingIcon = $('<i>', {
        class: 'fa fa-spinner fa-spin loading-icon',
        id: 'loadingIcon'
    });
    const suggestions = $('<ul>', {
        id: 'suggestions',
        class: 'suggestions-list'
    });
    const btn = $('<button>', {
        id: 'btn',
        text: '对比',
        class: 'search-btn',
        onclick: 'updateLine()'
    });

    const playBtn = $('<button>', {
        id: 'playBtn',
        text: '暂停',
        class: 'search-btn',
        onclick: 'play()'
    });

    for (let i = 0; i < input.length; i++) {
        btnDiv.append(input[i])
        if (i === 0) btnDiv.append('vs')
    }

    newDiv2.append(line);
    btnDiv.append(loadingIcon);
    btnDiv.append(suggestions);
    // btnDiv.append(btn);
    newDiv2.append(btnDiv);
    newDiv2.append(btn);
    newDiv2.append(playBtn);

    main.append(newDiv2);
    getData();
    inputHintBox();


}

//状态默认播放
var isPlaying = true;
function play() {
    if (isPlaying){
        isPlaying = false;
        $('#playBtn').text('播放');
        clearInterval(interval)
    } else {
        isPlaying = true;
        $('#playBtn').text('暂停');
        createInterVal()
    }

}

//创建一个自动对比歌手循环
let intervalList

//获取歌手列表并保存
getSingerList(1, 20).then(response => {
    intervalList = response
})
var i = 0;
function createInterVal() {
    interval = setInterval(e => {
        if (i >= intervalList.length - 1) {
            i = 0;
        }
        $('#inputSinger1').val(intervalList[i])
        $('#inputSinger2').val(intervalList[i+1])
        i+=2
        updateLine()
    },2000)
}

// 获取歌手基础信息
function getSingerBasicInfo(singerName) {
    // 返回一个 Promise 对象
    return new Promise((resolve, reject) => {
        $.ajax({
            url: "singerBasicInfo/getBasicInfo",
            type: "GET",
            data: {singerName: singerName}, // 修正参数名拼写错误（singeName → singerName）
            dataType: "json",
            success: function (data) {
                // 成功时将结果传递给 resolve
                resolve(data);
            },
            error: function (xhr) {
                console.error('请求失败:', xhr.responseText);
                // 失败时将错误传递给 reject
                reject(xhr.responseText);
            }
        });
    });
}

//更新图表
async function updateLine() {
    try {
        // 等待 Promise 完成并获取结果
        for (let i = 0; i < singerInfo.length; i++) {

            const result = await getSingerBasicInfo($('#inputSinger' + (i + 1)).val());
            // const result = await getSingerBasicInfo("周杰伦");
            singerInfo[i][0] = result[0].musicNum
            singerInfo[i][1] = result[0].mvNum
            singerInfo[i][2] = result[0].albumNum
            singerName[i] = result[0].singerName
        }

        myChart.setOption({
            series: [
                {name: singerName[0], data: singerInfo[0]},
                {name: singerName[1], data: singerInfo[1]}
            ]
        })

        // 在这里处理返回的数据（如更新DOM、业务逻辑等）
        // return result; // 可以返回给上层调用者
    } catch (error) {
        // 捕获错误
        console.error("处理失败:", error);
    }
}

// 获取数据并绘制折线图
function getData() {
    // 初始化图表
    if (!myChart) {
        myChart = echarts.init(document.getElementById('line'));
    } else {
        myChart.dispose(); // 关键：销毁旧实例
        myChart = echarts.init(document.getElementById('line'));
    }

    // 配置图表选项
    const option = {
        //标题
        title: {
            text: '歌手对比'
        },
        //提示框
        tooltip: {
            show: true,
            trigger: 'axis',
        },
        toolbox: {
            feature: {
                dataView: {},
                magicType: {type: ['line', 'bar', 'stack', 'tiled']},
                restore: {},
                saveAsImage: {},
            },
            orient: 'vertical',
        },
        //图例
        legend: {
            show: true
        },
        //x轴
        xAxis: {
            type: 'category',
            data: ["歌曲数量", "mv数量", "专辑数量"],
        },
        yAxis: {
            type: 'value',
        },
        series: [
            {
                type: 'line',
                name: singerName[0],
                data: singerInfo[0],
            },
            {
                type: 'line',
                name: singerName[1],
                data: singerInfo[1],
            }
        ],
    }

    myChart.setOption(option);
}



/**
 * 缓存top3资源
 * @type {null}
 */
let noPics = [];
let singerNames = [];

function getTopThree() {
    const noList = []
    const noTextList = []

    for (let i = 0; i < 3; i++) {
        noList.push($('#No' + (i + 1)))
    }
    for (let i = 0; i < 3; i++) {
        noTextList.push($('#No' + (i + 1) + 'Text'))
    }
    if (noPics.length === 0) {
        $.ajax({
            url: "/singerList/getTopThree",
            type: "GET",
            dataType: "json",
            success: function (data) {
                for (let i = 0; i < noList.length; i++) {
                    var singerName =
                        data[i].singerName.split('').length > 6 ?
                            data[i].singerName.substring(0, 6) + '...' :
                            data[i].singerName
                    if (i === 1) singerName = data[i].singerName.split('').length > 3 ? data[i].singerName.substring(0, 3) + '...' : data[i].singerName
                    noList[i].attr('src', data[i].pic)
                    noTextList[i].text(singerName)
                    noPics[i] = data[i].pic
                    singerNames[i] = singerName
                }
                console.log("图片通过请求加载..")
            },
            error: function (xhr) {
                console.error('请求失败:', xhr.responseText);
            }
        })
    } else {
        for (let i = 0; i < noList.length; i++) {
            noList[i].attr('src', noPics[i])
            noTextList[i].text(singerNames[i])
        }
        console.log("图片从缓存中加载..")
    }
}

function inputHintBox() {
    // DOM元素
    const $searchInput = [$('#inputSinger1'), $('#inputSinger2')];
    const $suggestionsList = $('#suggestions');
    const $loadingIcon = $('#loadingIcon');
    let currentIndex = -1;
    let lastRequest = null;
    //记录当前点击的输入框
    let currentInput = -1;

    // 输入事件处理
    $searchInput.forEach(data => {
        data.on('input', function () {
            const inputValue = $(this).val().trim();

            // 重置选中索引
            currentIndex = -1;

            // 如果输入为空，隐藏建议列表
            if (inputValue.length === 0) {
                $suggestionsList.hide();
                return;
            }

            // 取消上一次未完成的请求
            if (lastRequest) {
                lastRequest.abort();
            }

            // 显示加载状态
            $loadingIcon.show();

            // 发送AJAX请求到后端接口
            lastRequest = $.ajax({
                url: 'http://localhost:8080/test/test',  // 你的后端API地址
                method: 'GET',
                data: {
                    singerName: inputValue  // 发送搜索关键词
                },
                dataType: 'json',
                timeout: 5000,  // 5秒超时

                success: function (response) {
                    $loadingIcon.hide();

                    singerName = response.map(item => item.singerName);

                    // 检查响应是否有效
                    if (response) {
                        console.log(`从服务器获取到 ${singerName.length} 条结果`);
                        displaySuggestions(singerName, inputValue);
                        $suggestionsList.show();
                    } else {
                        console.log('服务器返回格式不正确');
                        showErrorMessage('数据格式错误');
                    }
                },

                error: function (xhr, status, error) {
                    $loadingIcon.hide();

                    if (status !== 'abort') {  // 不是主动取消的请求
                        console.log(`请求错误: ${status} - ${error}`);
                        showErrorMessage('获取数据失败，请重试');
                    } else {
                        console.log('请求已取消');
                    }
                }
            });
        });
        // currentClickInput()
    })

    // 显示建议列表
    function displaySuggestions(matches, inputValue) {
        // 清空现有列表
        $suggestionsList.empty();

        if (matches.length === 0) {
            $suggestionsList.append(`
                        <li class="no-results">没有找到匹配"${inputValue}"的结果</li>
                    `);
        } else {
            matches.forEach(item => {
                // 这里假设item是字符串，如果是对象可以用item.name等属性
                const itemText = typeof item === 'object' ? item.name : item;
                const lowerItem = itemText.toLowerCase();
                const lowerInput = inputValue.toLowerCase();
                const index = lowerItem.indexOf(lowerInput);

                let itemHtml;
                if (index !== -1) {
                    const before = itemText.substring(0, index);
                    const match = itemText.substring(index, index + inputValue.length);
                    const after = itemText.substring(index + inputValue.length);
                    itemHtml = `${before}<span class="highlight">${match}</span>${after}`;
                } else {
                    itemHtml = itemText;
                }

                const $li = $(`<li class="suggestion-item">${itemHtml}</li>`);

                // 存储原始数据，方便后续使用
                $li.data('originalData', item);

                // 点击选择
                // $searchInput[0].on('keyup', function(e) {
                $li.on('click', function () {
                    $searchInput[currentInput].val(itemText);
                    $suggestionsList.hide();
                    // 可以在这里添加选择后的回调处理
                    handleSelection($(this).data('originalData'));
                });
                $suggestionsList.append($li);
            });
        }
    }

    // 处理选中项
    function handleSelection(data) {
        // 这里可以添加选中后的处理逻辑
        console.log('选中的数据:', data);
    }

    // 显示错误信息
    function showErrorMessage(message) {
        $suggestionsList.empty().append(`
                    <li class="error-message">${message}</li>
                `).show();
    }

    // 键盘事件处理
    $searchInput.forEach(data => {
        data.on('keydown', function (e) {
            const $items = $suggestionsList.find('.suggestion-item');
            if ($items.length === 0) return;

            // 下箭头
            if (e.key === 'ArrowDown') {
                e.preventDefault();
                currentIndex = (currentIndex + 1) % $items.length;
                highlightSelection($items);
            }
            // 上箭头
            else if (e.key === 'ArrowUp') {
                e.preventDefault();
                currentIndex = (currentIndex - 1 + $items.length) % $items.length;
                highlightSelection($items);
            }
            // 回车键
            else if (e.key === 'Enter') {
                e.preventDefault();
                if (currentIndex >= 0) {
                    const $selected = $items.eq(currentIndex);
                    $searchInput[currentInput].val($selected.text());
                    // $searchInput.val($selected.text());
                    $suggestionsList.hide();
                    handleSelection($selected.data('originalData'));
                }
            }
            // ESC键
            else if (e.key === 'Escape') {
                $suggestionsList.hide();
            }
        });
    })

    function currentClickInput(index) {
        currentInput = index;
    }

    // 高亮选中项
    function highlightSelection($items) {
        $items.removeClass('active');
        $items.eq(currentIndex).addClass('active');

        // 滚动到可见区域
        const $activeItem = $items.eq(currentIndex);
        if ($activeItem.length) {
            const listTop = $suggestionsList.scrollTop();
            const listHeight = $suggestionsList.height();
            const itemTop = $activeItem.position().top - 375 + listTop;
            const itemHeight = $activeItem.height();

            // 如果项在可视区域上方
            if (itemTop < listTop) {
                $suggestionsList.scrollTop(itemTop);
            }
            // 如果项在可视区域下方
            else if (itemTop + itemHeight > listTop + listHeight) {
                $suggestionsList.scrollTop(itemTop + itemHeight - listHeight);
            }
        }
    }

    // 点击外部关闭下拉框
    $(document).on('click', function (e) {
        $searchInput.forEach(data => {
            data.on('click', function () {
                return false;
            })
        })

        for (let i = 0; i < $searchInput.length; i++) {
            if (!$searchInput[i].is(e.target) && !$suggestionsList.is(e.target) &&
                !$searchInput[i].has(e.target).length) {
                $suggestionsList.hide();
                break;
            }
        }

    });

    $('#inputSinger1').on('focus', function (e) {
        currentClickInput(0)
    })
    $('#inputSinger2').on('focus', function (e) {
        currentClickInput(1)
    })

    // 输入框聚焦时如果有内容则触发搜索
    $searchInput.forEach(data => {
        data.on('focus', function () {
            if ($(this).val().trim()) {
                $(this).trigger('input');
            }
        });
    })
}
